// packageA/pages/partAdd/partAdd.js
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,    
    //适用型号id
    brandId:[],    
    //适用型号选择框
    showBrand:false,
    //适用型号列表
    brandList:[],
    //全选/反选
    checkedAll: false,
    //选项数量:
    checkLen:0,
    //上传路径
    ossUploadUrl: app.globalData.ossUrl
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('配件传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        //获取修改数据
        this.getInfo();
      }
    }
  },

  //提交表单
  confirmForm(e){
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;  

    //配件名称必填
    let name=obj.name.trim();
    if(!this.formNotEmpty(name,'nameMessage','请输入配件名称')){
      return;
    }

    //处理厂家
    let fList=[];
    if(editInfo.factories && editInfo.factories.length){
      fList=editInfo.factories;

      //转化为数字
      fList.forEach(item => {
        item.purchasePrice=Number(item.purchasePrice);
        item.salePrice=Number(item.salePrice);
      });

      //是否大于0
      let flag1=false,flag2=false;

      flag1=fList.every(item=>{
        return item.purchasePrice>0;
      });

      flag2=fList.every(item=>{
        return item.salePrice>0;
      });

      if(flag1 && flag2){
      }else{
        Toast.fail('进价和售价为大于0的数字');
        return;
      }

      //型号必填
      let flag3=false;
      flag3=fList.every(item=>{
        return item.brands.length>0;
      });
      if(!flag3){
        Toast.fail('请选择适用型号');
        return;
      }
    }

    let param={
      className:'partsFactory',
      data:{
        id: td.id,
        name: name,
        pic: editInfo.pic,
        remark: obj.remark.trim(),
        factories: fList
      }
    }

    //console.log(param.data);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  //获取修改数据
  getInfo(){
    let param = { 
      id: this.data.id,
      page: 1,
      pageSize: 10
    }

    CommonService.partList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //处理厂家
        if(result.factories && result.factories.length){
          result.factories.forEach(item => {
            if(item.brands && item.brands.length){
              let arr=[];
              item.brands.forEach(item2 => {
                arr.push(item2.name);
              });              
              item.self_brand=arr;
            }	
          });
        }

        console.log('配件信息回显');
        console.log(result);

        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },  

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  }, 

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    if(imgUrls.length){
      let pic='editInfo.pic';
      this.setData({
        [pic]: imgUrls
      })
    }  
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    wx.previewImage({
      current: src,
      urls: detail
    })
  },

  //获取输入的值
  onGetValue(e){
    let dataset=e.currentTarget.dataset;
    let val=e.detail;
    let list=this.data.editInfo.factories;
   
    list.forEach((item,index) => {
      if(index==dataset.index){
        item[dataset.field]=val.trim();
      }
    }); 

    let factories='editInfo.factories';
    this.setData({ 
      [factories]: list,
      disabled: false
	})
  },

  //显示适用型号选择框
  onShowBrand(e){
    if(!this.data.paramObj.isRead){
      let dataset=e.currentTarget.dataset;

      this.setData({
        showBrand: true,
        currentIndex: dataset.index,
        currentLoop: dataset.current
      })
  
      //查询型号
      this.getBrandList();
    }
  },

  //隐藏适用型号选择框
  onCloseBrand(){
    this.setData({
      showBrand: false,
      checkedAll: false,
      disabled: false
    })
  },

  //查询型号
  getBrandList(){
    this.setData({
      brandList: []
    })

    let currentLoop=this.data.currentLoop;

    let param = {
      isAuth: false,
      className: 'factoryEquipmentType',
      data: {
        searchAll: true,
        factoryId: currentLoop.factory.id,
        selectFields: ['id','name','factoryId']
      }
    }  

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        this.setData({
          brandList: result,
          checkLen: result.length
        })
      }
    }).catch((error) => {
    })
  },

  //确认型号
  onConfirmBrand(){
    let list=this.data.brandList;
    let idArr=this.data.brandId;

    let names=[];
    let arr=[];
    for(let i=0;i<list.length;i++){
      idArr.forEach(item => {
        if (item==list[i].id){
          names.push(list[i].name);
          arr.push({
            id: list[i].id,
            name: list[i].name
          });
        }
      });
    }

    let currentIndex=this.data.currentIndex;
    let loopList=this.data.editInfo.factories;

    loopList.forEach((item,index) => {
      if(index==currentIndex){
        item.self_brand=names;
        item.brands=arr;
      }
    });

    let factories='editInfo.factories';
    this.setData({ 
      [factories]: loopList
	  })

    this.onCloseBrand();
  },
  
  //点击全选
  onChangeAll(event) {
    this.setData({
      checkedAll: event.detail
    })

    if(event.detail){
      let list=this.data.brandList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+"");
      })
      this.setData({
        brandId: arr,
      })
    }else{
      this.setData({
        brandId: [],
      })
    }
  },

  //勾选
  onChangeBrand(event) {
    this.setData({
      brandId: event.detail
    })

    if(event.detail.length==this.data.checkLen){
      this.setData({
        checkedAll: true,
      })
    }else{
      this.setData({
        checkedAll: false,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})